package com.itita.ww2.model.user;

import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.itita.ww2.utils.DevKeyUtil;
import com.itita.ww2.utils.TimeUtil;

/**
 * 玩家的时间计划
 * @author NorthLan
 *
 */
public class DevTime {
	private transient String key;
	private long startTime; // 开始时间
	private int duration; // 持续时间(seconds)
	private long endTime; // 结束时间
	private DevTimeType type; // 该时间的种类

	public static enum DevTimeType {
		UPGRADE(1), // 升级
		PRODUCE, // 生产
		RESOURCE, // 资源
		FATIGUE, // 疲劳
		;

		private int value;

		private DevTimeType() {
			this(Counter.nextValue);
		}

		private DevTimeType(int value) {
			this.value = value++;
			Counter.nextValue = value;
		}

		public int getValue() {
			return value;
		}

		@Override
		public String toString() {
			return super.toString().toLowerCase();
		}

		public static DevTimeType keyValueOf(String val) {
			for (DevTimeType ret : values()) {
				if (val.startsWith(ret.toString())) {
					return ret;
				}
			}
			return null;
		}

		private static class Counter {
			private static int nextValue = 0;
		}
	}

	public DevTime(DevTimeType type, String code, long startTime, int duration, long endTime) {
		this.type = type;
		this.startTime = startTime;
		this.duration = duration;
		this.endTime = endTime;
		this.key = DevKeyUtil.combineKey(type.toString(), code);
	}

	private DevTime(String key, long startTime, int duration, long endTime) {
		this.type = DevTimeType.keyValueOf(key);
		this.startTime = startTime;
		this.duration = duration;
		this.endTime = endTime;
		this.key = key;
	}

	public static String genericKey(DevTimeType type, String code) {
		return DevKeyUtil.combineKey(type.toString(), code);
	}

	public boolean isTimesUp() {
		long nowTime = TimeUtil.getUtcNowMillis();
		return nowTime >= this.endTime;
	}

	public void updateEndTime(long endTime) {
		this.endTime = endTime;
	}

	/*
	 * ******************** Getters
	 */
	public long getStartTime() {
		return startTime;
	}

	public int getDuration() {
		return duration;
	}

	public long getEndTime() {
		return endTime;
	}

	public String getKey() {
		return key;
	}

	public DevTimeType getType() {
		return type;
	}

	public static DevTime newFromJsonData(String key, ISFSObject data) {
		return new DevTime(key, data.getLong("startTime"), data.getInt("duration"), data.getLong("endTime"));
	}

	public ISFSObject toSFSObject() {
		ISFSObject ret = SFSObject.newInstance();
		ret.putLong("startTime", this.startTime);
		ret.putLong("endTime", this.endTime);
		ret.putInt("duration", this.duration);
		return ret;
	}
}
